let page = 1; // 当前第一页
let limit = 2; // 每页2条数据
let count = 0; //总页数，默认0

const getUserList = () => {
  let xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function () {
    if ( xhr.readyState === 4 && xhr.status === 200 ) {
      let res = JSON.parse( xhr.responseText );
      if ( res.code === 0 ) {
        console.log( res );  // {code, msg, count, data}
        count = Math.ceil( res.count / limit );
        renderTable( res.data )  // 渲染表格
        renderPage( count )//渲染分页
      } else {
        console.log( res );
      }
    }
  }
  xhr.open( 'get', "http://127.0.0.1:80/user/getAll?pageNow=" + page + "&pageSize=" + limit );
  xhr.send();
}
//渲染表格
const renderTable = ( arr ) => {
  let userTbody = document.getElementById( 'userTbody' );
  userTbody.innerHTML = '';
  let strHtml = '';
  arr.forEach( ( el, index ) => {
    strHtml += `<tr data-id="${ el.uid }">
                  <td>
                    <input type="checkbox">
                  </td>
                  <td>${ el.uaccess }</td>
                  <td>${ el.uname }</td>
                  <td>
                    <div class="custom-control custom-switch">
                      <input type="checkbox" class="custom-control-input" id="customSwitch${ index }" ${ el.ustate === '1' ? 'checked' : '' }>
                      <label class="custom-control-label" for="customSwitch${ index }">${ el.ustate === '1' ? '启用' : '禁用' }</label>
                    </div>
                  </td>
                  <td>
                    <button type="button" class="btn btn-link   text-info btn-roles">角色选择</button>
                    <button type="button" class="btn btn-link   text-danger btn-delete">删除</button>
                    <button type="button" class="btn btn-link   text-primary btn-modify">修改</button>
                  </td>
                </tr>`;
  } );
  userTbody.innerHTML = strHtml;
}
//渲染分页
const renderPage = ( count ) => {
  let strHtml = '';
  let userPagination = document.getElementById( 'userPagination' )
  userPagination.innerHTML = ''
  strHtml += `<li class="page-item disabled">
  <a class="page-link">Previous</a>
</li>`;
  for ( let i = 1; i <= count; i++ ) {
    strHtml += ` <li class="page-item ${ i === page ? 'active' : '' }"><a class="page-link" href="#">${ i }</a></li>`
  }
  strHtml += `<li class="page-item">
  <a class="page-link" href="#">Next</a>
</li>`
  userPagination.innerHTML = strHtml;
}

window.onload = getUserList;
